/**
 * Author(s): xuming.Wong <xuming.Wong@gmail.com>
 */
#include "TerrainTextureArchive.h"

#include "GPKArchiveManager.h"
#include "NgFileSystem.h"
#include "GameEngine.h"


namespace PQEngine
{
	const std::string TerrainTextureArchive::TERRAIN_TEXTURE_ARCHIVE_NAME="TerrainTexture";//system made with a underscore before it
	TerrainTextureArchive::TerrainTextureArchive()
		: _selectedIndex(0),_archive(0)
	{
		bool success=GNgGPKArchiveManager.hasArchive(TERRAIN_TEXTURE_ARCHIVE_NAME);
		if(!success){
			_archive=GNgGPKArchiveManager.createArchive(TERRAIN_TEXTURE_ARCHIVE_NAME);
		}else{
			_archive=GNgGPKArchiveManager.getArchive(TERRAIN_TEXTURE_ARCHIVE_NAME);
		}

		assert(_archive);
		
		int cnt=_archive->getNumFile();
		for(int i=0;i<cnt;i++){
			std::string name=_archive->getFileName(i);
			_nameList.push_back(name);

			loadTexture(i);
		}

	}

	void TerrainTextureArchive::loadTexture(int index)
	{
		
		GPKFile* file=_archive->getFile(index);
		if(!file||!file->ok()){
			return;
		}

		file->open();
		int size=file->length();
		char* buf=new char[size];
		file->read(buf,size);
		file->close();

		Ogre::DataStreamPtr stream=Ogre::DataStreamPtr(new Ogre::MemoryDataStream(buf,size));

		Ogre::Image img;
		img.load(stream);
		delete buf;

		Ogre::String textureName=_archive->getFileName(index);
		
		Ogre::TextureManager::getSingleton().loadImage(textureName,
			GameEngine::TERRAIN_RESOURCE_GROUP_NAME,
			img);
		
		
	}

	bool TerrainTextureArchive::addTextureFromLocalFS(std::string filePath)
	{
		assert(_archive);
		bool success=_archive->addFile(filePath);

		if(success){
			std::string name=NgFileSystem::getPathLastNode(filePath);
			_nameList.push_back(name);
		}
		return success;

	}

	GPKFile* TerrainTextureArchive::getTextureFile(int index)
	{
		assert(_archive);
		GPKFile* file=_archive->getFile(index);

		return file;
	}

	GPKFile* TerrainTextureArchive::getTextureFile(std::string name)
	{
		assert(_archive);
		GPKFile* file=_archive->getFile(name);

		return file;
	}

}
